/* $RCSFile: MagicError.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice/app_support/MagicError.aspx.cs $
 * $log$
 * Revision 20 2010/08/09 10:51:18  christian.surieux
 *   Added Log comment to all .aspx .ascx .master files
 * Revision 19 2010/08/09 09:43:42  christian.surieux
 *   Added Log to cs sources files
 * Revision 6 2010/08/06 19:56:24  christian.surieux
 *   Added Log to All cs files
 */

using System;
using System.Diagnostics;
using System.Data;
using System.Collections;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Xml;
using System.Globalization;

using AddonNice.Diagnostics;
using AddonNice.UI;
using AddonNice.Core;
using AddonNice.Helpers;
using AddonNice.Settings;
using AddonNice.Settings.Cache;

using Utils     =   AddonNice.Helpers.Utils;
using Trace2    =   System.Diagnostics.Trace;

namespace AddonNice.Error
{
    /// <summary>
    /// MagicError page : This is a mandatory component of the magic utls systems
	/// You must set "~/app_support/MagicError.aspx" as the destination for http 404 (not found) errors in IIS
    /// </summary>
    public partial class MagicError : ADNPage
	{

		public void Page_Error(object sender,EventArgs e)
		{
			Response.Redirect(Config.CriticalErrorRedirect, true);
		}

        public override string ReturnUrl
        {
            get
            {
                return base.ReturnUrl;
            }
            set
            {
                // do nothing we don't want to be a return url
                if (PageTraceSwitch.Sw.TraceVerbose)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]StdAuxPage ReturnUrl SET called but value not stored: '{0}'.",value), PageTraceSwitch.Sw.Info);
            }
        }

        /// <summary>
		/// Directly executed to avoid any pb with autoeventWiredUp
		/// </summary>
		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad (e);

			if (MagicTraceSwitch.Sw.TraceError)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad BEG RawUrl: {0}.", Request.RawUrl),MagicTraceSwitch.Sw.Info);

			string _rawUrl = Context.Request.RawUrl.ToLower(CultureInfo.InvariantCulture);
			if (!_rawUrl.EndsWith(".css") &&
				!_rawUrl.EndsWith(".js") &&
				!_rawUrl.EndsWith(".jpg") &&
				!_rawUrl.EndsWith(".png") &&
				!_rawUrl.EndsWith(".gif") &&
		        (Request.QueryString[0] != null) 
                )
			{
				if (MagicTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad Request.QueryString[0]: {0}.", Request.QueryString[0]),MagicTraceSwitch.Sw.Info);
				// is this a "MagicUrl" request
				if (Request.QueryString[0].StartsWith("404;http://"))
				{
					Hashtable magicUrlList		    =   null;
					string redirectUrl			    =   string.Empty;
					int qPartPos				    =   Request.QueryString[0].LastIndexOf("/") + 1;
					string qPart				    =   (qPartPos < Request.QueryString[0].Length) ? Request.QueryString[0].Substring(qPartPos) : string.Empty;
					if (MagicTraceSwitch.Sw.TraceVerbose)
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad qPart: {0}.", qPart),MagicTraceSwitch.Sw.Info);
					if ( qPart.Length > 0 )
					{
						if (MagicTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad qPart: {0}.", qPart),MagicTraceSwitch.Sw.Info);
						if ( Utils.IsInteger(qPart) )
							redirectUrl             =   HttpUrlBuilder.BuildUrl(Int32.Parse(qPart));
						else
						{
							magicUrlList			=   GetMagicUrlList(portalSettings.PortalID);
							string EncQPart			=   HttpUtility.HtmlEncode(qPart);
							if ( magicUrlList != null && magicUrlList.ContainsKey(EncQPart) )
							{
								redirectUrl			=   HttpUtility.HtmlDecode(magicUrlList[EncQPart].ToString());
								if (MagicTraceSwitch.Sw.TraceVerbose)
                                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad redirectUrl: {0}.", redirectUrl),MagicTraceSwitch.Sw.Info);
								if (Utils.IsInteger(redirectUrl))
									redirectUrl		=   HttpUrlBuilder.BuildUrl(Int32.Parse(redirectUrl));
							}
						}
						if (redirectUrl.Length != 0)
						{
							if (MagicTraceSwitch.Sw.TraceVerbose)
                                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad END redirectUrl: {0}.", redirectUrl),MagicTraceSwitch.Sw.Info);
							Response.Redirect(redirectUrl, true);
						}
					}
				}
			}
			// not a magic URL, transfert to smartError
			if (MagicTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError OnLoad END not a Magic Url transfering to : {0}.", Config.SmartErrorRedirect),MagicTraceSwitch.Sw.Info);
			Server.Transfer(Config.SmartErrorRedirect,false);
		}

		/// <summary>
		/// 
		/// </summary>
		/// <param name="portalID"></param>
		/// <returns></returns>
		private Hashtable GetMagicUrlList(int portalID)
		{
			if (MagicTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError GetMagicUrlList BEG portalID: {0}.", portalID),MagicTraceSwitch.Sw.Info);
			Hashtable result    =  new Hashtable();
			HttpContext.Current.Application.Lock();
			try
			{
				DataTable tb = (DataTable)HttpContext.Current.Application["MagicUrls"];
				foreach (DataRow rw in tb.Rows)
				{
					try
					{
						if ( ((int)rw["PortalID"]) == portalID )
							result.Add((string)rw["MagicKey"], HttpUtility.HtmlDecode((string)rw["MagicValue"]));
					}
					catch(Exception ex)
					{
			            if (MagicTraceSwitch.Sw.TraceError)
                            Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicError GetMagicUrlList ex: {0}.", ex),MagicTraceSwitch.Sw.Info);
                    }
				}
			}
			catch (Exception ex2)
			{ 
	            if (MagicTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]MagicError GetMagicUrlList ex2: {0}.", ex2),MagicTraceSwitch.Sw.Info);
            }
			finally
			{
				HttpContext.Current.Application.UnLock();
			}
			if (MagicTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]MagicError GetMagicUrlListt END portalID: {0}, Count: {1}.", portalID,result.Count),MagicTraceSwitch.Sw.Info);
			return result;
		}

       
		#region Std Overrides

        override protected void OnInit(EventArgs e)
		{
			InitializeComponent();
			base.OnInit(e);
		}

		private void InitializeComponent() 
		{    
            Error   +=  new EventHandler(this.Page_Error);
		}

        #endregion
    }
}